package com.ecgsystem.activity;

import com.ecgsystem.constants.Commons;
import com.ecgsystem.constants.Constants;
import com.ecgsystem.R;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Configuration extends Activity implements Constants {

	private EditText serverET;
	private EditText tcpET;
	private EditText udpET;

	private String server;
	private int tcpPort;
	private int udpPort;

	private Button setupBT;
	private Button cancelBT;
	private Button resetBT;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configuration);

		serverET = (EditText) findViewById(R.id.editText_Server);
		tcpET = (EditText) findViewById(R.id.editText_TCPPort);
		udpET = (EditText) findViewById(R.id.editText_UDPPort);

		setupBT = (Button) findViewById(R.id.button_SetupConf);
		cancelBT = (Button) findViewById(R.id.button_CancelConf);
		resetBT = (Button) findViewById(R.id.button_ResetDefault);

		SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
		server = pref.getString(PREFS_SERVER, Commons.UDP_SERVER_ADDRESS);
		tcpPort = pref.getInt(PREFS_TCPPORT, Commons.TCP_PORT);
		udpPort = pref.getInt(PREFS_UDPPORT, Commons.UDP_PORT);

		serverET.setText(server);
		tcpET.setText(Integer.toString(tcpPort));
		udpET.setText(Integer.toString(udpPort));

		setupBT.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (checkInput() == true) {
					Commons.UDP_SERVER_ADDRESS = server;
					Commons.TCP_PORT = tcpPort;
					Commons.UDP_PORT = udpPort;

					saveServerDetails();

					finish();
				}
			}
		});

		cancelBT.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
		
		resetBT.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Commons.UDP_SERVER_ADDRESS = "ecgsystem.myvnc.com";
				Commons.TCP_PORT = 5002;
				Commons.UDP_PORT = 5001;
				
				saveServerDetails();

				finish();
			}
		});
	}

	private void saveServerDetails() {
		getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
				.putString(PREFS_SERVER, Commons.UDP_SERVER_ADDRESS)
				.putInt(PREFS_TCPPORT, Commons.TCP_PORT)
				.putInt(PREFS_UDPPORT, Commons.UDP_PORT).commit();
	}

	private boolean checkInput() {
		try {
			server = serverET.getText().toString();
			tcpPort = Integer.valueOf(tcpET.getText().toString());
			udpPort = Integer.valueOf(udpET.getText().toString());
		} catch (Exception e) {
			Toast.makeText(this, "Input Error", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
}
